<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\controller\api\store\merchant;

use app\common\repositories\store\MerchantTakeRepository;
use app\common\repositories\store\service\StoreServiceRepository;
use app\common\repositories\system\config\ConfigClassifyRepository;
use app\common\repositories\system\config\ConfigRepository;
use app\common\repositories\system\config\ConfigValueRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use app\validate\merchant\MerchantTakeValidate;
use app\validate\merchant\MerchantUpdateValidate;
use crmeb\jobs\ChangeMerchantStatusJob;
use think\App;
use crmeb\basic\BaseController;
use think\db\exception\DbException;
use think\facade\Queue;

class BasicConfig extends BaseController
{
    protected $repository;
    protected $userInfo;

    /**
     * @var ConfigClassifyRepository
     */
    protected $repositoryVal;

    /**
     * ProductCategory constructor.
     * @param App $app
     * @param ConfigRepository $repository
     * @param ConfigValueRepository $repository
     */
    public function __construct(App $app, ConfigRepository $repository, ConfigValueRepository $repositoryVal)
    {
        parent::__construct($app);
        $this->repository = $repository;
        $this->repositoryVal = $repositoryVal;
        $this->userInfo =$this->request->isLogin() ? $this->request->userInfo():null;
    }

    /**
     * @param $id
     * @return mixed
     * 获取配置信息
     */
    public function basic($id,ConfigClassifyRepository $configClassifyRepository)
    {
        if (!$configClassifyRepository->keyExists('mer_base') || !($configClassfiy = $configClassifyRepository->keyByData('mer_base')))
            return app('json')->fail('配置分类不存在');
        if ($configClassifyRepository->existsWhere(['pid' => $configClassfiy->config_classify_id]))
            $form = $this->repository->tabForm($configClassfiy, $id);
        else
            $form = $this->repository->cidByFormRule($configClassfiy, $id);
        return app('json')->success(formToData($form));
    }

    /**
     * @param $key
     * @return void
     * 修改配置信息
     */
    public function basicUpd($key = 'mer_base')
    {
        $formData = $this->request->post();

        $mer_id = $formData['mer_id'];
        unset($formData['mer_id']);
        if (!count($formData)) return app('json')->fail('保存失败');
        /** @var ConfigClassifyRepository $make */
        $make = app()->make(ConfigClassifyRepository::class);
        if (!($cid = $make->keyById($key))) return app('json')->fail('保存失败');
        $children = array_column($make->children($cid, 'config_classify_id')->toArray(), 'config_classify_id');
        $children[] = $cid;
        $this->repositoryVal->save($children, $formData, $mer_id);
        return app('json')->success('保存成功');
    }


    /**
     * @param $id
     * @param MerchantTakeRepository $repository
     * @return mixed
     * 2023.09.16
     * 获取商户信息
     */
    public function info($id,MerchantTakeRepository $repository)
    {
        $merchant = app()->make(MerchantRepository::class)->get($id);
        $append = ['merchantCategory', 'merchantType', 'mer_certificate','margin_remind_status'];
        if ($merchant->is_margin == -10)
            $append[] = 'refundMarginOrder';

        $data = $merchant->append($append)->hidden(['mark', 'reg_admin_id', 'sort'])->toArray();
        $delivery = $repository->get($id) + systemConfig(['tx_map_key']);
        $data = array_merge($data,$delivery);
        $data['sys_bases_status'] = systemConfig('sys_bases_status') === '0' ? 0 : 1;

        return app('json')->success($data);
    }


    /**
     * @param MerchantUpdateValidate $validate
     * @return mixed
     * @author xaboy
     * @day 2020/6/25
     */
    public function infoUpd(MerchantUpdateValidate $validate, MerchantTakeValidate $takeValidate, MerchantTakeRepository $repository)
    {

        $type = $this->request->param('type',1);
        $mer_id = $this->request->param('mer_id');
        $merchant = app()->make(MerchantRepository::class)->get($mer_id);
        if ($type == 2) {
            $data = $this->request->params([
                'mer_info',
                'mer_certificate',
                'service_phone',
                'mer_avatar',
                'mer_banner',
                'mer_state',
                'mini_banner',
                'mer_keyword',
                'mer_address',
                'long',
                'lat',
                ['delivery_way',[2]],
            ]);
            $validate->check($data);
            $sys_bases_status = systemConfig('sys_bases_status') === '0' ? 0 : 1;
            if ($sys_bases_status && empty($data['mer_certificate']))
                return app('json')->fail('店铺资质不可为空');

            app()->make(ConfigValueRepository::class)->setFormData([
                'mer_certificate' => $data['mer_certificate']
            ], $mer_id);
            unset($data['mer_certificate']);

            foreach ($data['delivery_way'] as $datum) {
                if ($datum == 1) {
                    $takeData = $this->request->params(['mer_take_status', 'mer_take_name', 'mer_take_phone', 'mer_take_address', 'mer_take_location', 'mer_take_day', 'mer_take_time']);
                    $takeValidate->check($takeData);
                    $repository->set($mer_id, $takeData);
                    break;
                }
            }
            $delivery_way = implode(',',$data['delivery_way']);
            if (count($data['delivery_way']) == 1 && $data['delivery_way'] != $merchant->delivery_way) {
                app()->make(ProductRepository::class)->getSearch([])
                    ->where('mer_id',$merchant->mer_id)
                    ->update(['delivery_way' => $delivery_way]);
            }

            $data['delivery_way'] = $delivery_way;

        } else {
            $data = $this->request->params(['mer_state']);

            if ($merchant->is_margin == 1 && $data['mer_state'] == 1)
                return app('json')->fail('开启店铺前请先支付保证金');

            if ($data['mer_state'] && !$merchant->sub_mchid && systemConfig('open_wx_combine'))
                return app('json')->fail('开启店铺前请先完成微信子商户入驻');
        }

        $merchant->save($data);
        Queue::push(ChangeMerchantStatusJob::class, $mer_id);
        return app('json')->success('修改成功');
    }


    /**
     * @param StoreServiceRepository $repository
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 客服列表
     */
    public function clerkList(StoreServiceRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where['mer_id'] = $this->request->get('mer_id','');
        return app('json')->success($repository->getList($where, $page, $limit));
    }


    /**
     * @param StoreServiceRepository $repository
     * @return mixed
     * @throws DbException
     * 修改客服状态
     */
    public function clerkChangeStatus(StoreServiceRepository $repository)
    {
        $mer_id = $this->request->param('mer_id','');
        $status = $this->request->param('status');
        $id = $this->request->param('id','');
        if (!$repository->merExists($mer_id, $id))
            return app('json')->fail('数据不存在');
        $repository->update($id, ['is_open' => $status == 1 ? 1 : 0]);
        return app('json')->success('修改成功');
    }

}
